<template>
  <div class="expert-management-container page-common-layout">
    <div class="serach-conditions-container">
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <a-row>
          <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="5">
            <a-form-model-item>
              <a-select
                showSearch
                :filter-option="filterOption"
                v-model="form.tenantCode"
                :loading="projectLoading"
                placeholder="请选择项目"
                @change="changeProject($event)"
              >
                <a-select-option
                  :value="item.proCode"
                  v-for="item in projectSoucre"
                  :key="item.uuid"
                >
                  {{ item.proName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="4">
            <a-form-model-item label="评审开始时间" prop="startDate">
              <a-date-picker
                v-model="form.startDate"
                :defaultPickerValue="proInfo.uploadEndDate"
                :disabled-date="disabledStartDate"
                :show-time="false"
                format="YYYY-MM-DD "
                valueFormat="YYYY-MM-DD "
                placeholder="请选择时间"
                style="width: 100%"
                :disabled="show"
                @change="startDateChange($event)"
              />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="4">
            <a-form-model-item label="评审结束时间" prop="endDate">
              <a-date-picker
                v-model="form.endDate"
                :disabled-date="disabledEndDate"
                :defaultPickerValue="form.startDate"
                :show-time="false"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
                placeholder="请选择时间"
                style="width: 100%"
                :disabled="show || !form.startDate"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            v-if="show && leaderSource.length > 0"
            :xs="24"
            :sm="24"
            :md="24"
            :lg="12"
            :xl="12"
            :xxl="5"
          >
            <a-form-model-item label="指定组长" prop="leaderId">
              <a-select
                placeholder="请选择指定组长"
                allowClear
                :loading="leaderLoading"
                v-model="form.leaderId"
                :disabled="!dateButton"
              >
                <a-select-option
                  :value="item.uuid"
                  v-for="item in leaderSource"
                  :key="item.uuid"
                >
                  {{ item.expertName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24" :md="24" :lg="12" :xl="12" :xxl="4">
            <a-button
              v-if="!show && tableData.length == 0"
              type="primary"
              @click="saveDate()"
              v-action:zjyq_add
            >
              确定
            </a-button>
            <a-button
              v-if="show && leaderSource.length > 0 && dateButton"
              type="primary"
              @click="saveLeader()"
              v-action:zjyq_add
            >
              确定
            </a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <div class="table-container">
      <div class="header" header="专家邀请"></div>
      <div class="main">
        <vxe-table
          ref="xTable"
          height="100%"
          align="center"
          show-overflow
          show-header-overflow
          border="inner"
          :data="tableData"
          :column-config="{ resizable: true }"
          size="small"
          :loading="loading"
        >
          <vxe-column type="seq" width="80" title="序号"></vxe-column>
          <vxe-column field="evaluationName" title="一级评价指标"> </vxe-column>
          <vxe-column field="expertCount" title="专家人数（人）"> </vxe-column>
          <vxe-column field="expertName" title="专家姓名"> </vxe-column>
          <vxe-column
            field="operate"
            width="220"
            title="操作"
            fixed="right"
            align="left"
          >
            <template #default="{ row }">
              <div class="text-button-group">
                <a-button
                  v-if="row.expertCount == 0 && dateButton"
                  type="link"
                  @click="gotoInvite(row)"
                  v-action:zjyq_edit
                >
                  邀请专家
                </a-button>
                <a-button
                  v-if="row.expertCount != 0"
                  type="link"
                  @click="gotoDetail(row)"
                >
                  查看
                </a-button>
                <a-button
                  v-if="row.expertCount != 0 && dateButton"
                  type="link"
                  @click="gotoEdit(row)"
                  v-action:zjyq_edit
                >
                  编辑
                </a-button>
              </div>
            </template>
          </vxe-column>
          <template #empty>
            <a-empty
              description="暂无数据，请先设置“评审开始时间”“评审结束时间”"
            />
          </template>
        </vxe-table>
      </div>
    </div>
    <!-- 邀请专家弹窗 -->
    <inviteModal
      :visible.sync="inviteModalVisible"
      :parameter="parameter"
      :key="inviteModalKey"
    ></inviteModal>
    <!-- 一键通知弹窗 -->
    <oneKeyNotice
      :visible.sync="oneKeyNoticeVisible"
      :parameter="parameter"
      :key="oneModalKey"
    ></oneKeyNotice>
  </div>
</template>
<script>
import moment from "moment";
import { axios } from "@/utils/request";
import inviteModal from "./components/inviteModal";
import oneKeyNotice from "./components/oneKeyNotice";
import { getNowFormatDate } from "@/utils/util";
import { getPZGCProList } from "@/api/qualityEngineering";
export default {
  components: {
    inviteModal,
    oneKeyNotice,
  },
  data() {
    return {
      loading: false,
      show: true,
      form: {
        tenantCode: undefined,
        startDate: "",
        endDate: "",
        leaderId: undefined,
      },
      rules: {
        startDate: [
          { required: true, message: "请选择开始时间", trigger: "change" },
        ],
        endDate: [
          { required: true, message: "请选择结束时间", trigger: "change" },
        ],
        leaderId: [
          { required: true, message: "请选择组长", trigger: "change" },
        ],
      },
      tableData: [],
      //邀请专家弹窗
      inviteModalVisible: false,
      inviteModalKey: 0,
      //一键通知弹窗
      oneKeyNoticeVisible: false,
      oneModalKey: 1,
      parameter: {
        uuid: "",
        text: "",
        tenantCode: "",
      },
      //组长下拉框
      leaderSource: [],
      leaderLoading: false,
      dateButton: false,
      //项目信息
      proInfo: {},
      //项目下拉框
      projectSoucre: [],
      projectLoading: false,
    };
  },
  mounted() {
    this.getProjectData();
  },
  methods: {
    changeProject(e) {
      this.proInfo = this.projectSoucre.find((v) => v.proCode == e);
      this.form.startDate = "";
      this.form.endDate = "";
      this.form.leaderId = undefined;
      this.getData();
    },

    //提交时间
    saveDate() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form } = this;
          let formJson = {
            tenantCode: form.tenantCode,
            startTime: form.startDate,
            endTime: form.endDate,
          };
          axios
            .post(`/probusiness/qeProjectExpert/saveProjectData`, formJson, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.getData();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {});
        }
      });
    },
    //保存组长
    saveLeader() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form } = this;
          let formJson = {
            leaderId: form.leaderId,
            tenantCode: form.tenantCode,
          };
          axios
            .post(`/probusiness/qeProjectExpert/saveLeaderData`, formJson, {
              headers: {
                "Content-Type": "application/json",
              },
            })
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.getData();
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {});
        }
      });
    },
    getData() {
      Promise.all([
        this.getGroupLeaderList(),
        this.getDetailLeader(),
        this.getTableData(),
      ]).then(() => {});
    },
    //查询项目下拉框
    getProjectData() {
      this.projectLoading = true;
      return new Promise((resolve, reject) => {
        getPZGCProList({ type: 1 })
          .then((res) => {
            this.projectSoucre = res?.data ?? [];
            this.proInfo = this.projectSoucre?.[0] ?? {};
            this.form.tenantCode = this.proInfo?.proCode ?? undefined;
            if (!this.form.tenantCode) {
              return;
            }
            this.getData();
            resolve();
          })
          .catch((_) => {
            this.proInfo = {};
            this.form.tenantCode = undefined;
            this.projectSoucre = [];
            reject();
          })
          .finally((_) => {
            this.projectLoading = false;
          });
      });
    },
    //查看组长
    getDetailLeader() {
      return new Promise((resolve, reject) => {
        let { form } = this;
        axios
          .post(
            `/probusiness/qeProjectExpert/getLeaderInfo`,
            { tenantCode: form.tenantCode },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.form.leaderId = data?.uuid || undefined;
            resolve();
          })
          .catch((_) => {
            this.form.leaderId = undefined;
            reject();
          })
          .finally((_) => {});
      });
    },
    //查询组长下拉框
    getGroupLeaderList() {
      this.leaderLoading = true;
      return new Promise((resolve, reject) => {
        let { tenantCode } = this.form;
        axios
          .post(
            `/probusiness/qeProjectExpert/getLeaderList`,
            {
              tenantCode,
            },
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            let { data } = res;
            this.leaderSource = data || [];
            resolve();
          })
          .catch((_) => {
            this.leaderSource = [];
            reject();
          })
          .finally((_) => {
            this.leaderLoading = false;
          });
      });
    },
    //查询列表
    getTableData() {
      this.loading = true;
      return new Promise((resolve, reject) => {
        let { tenantCode } = this.form;
        axios
          .post(
            `/probusiness/qeProjectExpert/getFirstList?tenantCode=${tenantCode}`,
            {},
            {
              headers: {
                "Content-Type": "application/json",
              },
            }
          )
          .then((res) => {
            this.tableData = res.data || [];
            if (this.tableData.length > 0) {
              this.show = true;
              let item = this.tableData[0] || {};
              this.form.startDate = item.startTime;
              this.form.endDate = item.endTime;
              this.dateButton = moment(getNowFormatDate()).isSameOrBefore(
                this.form.endDate
              );
            } else {
              this.show = false;
            }
            resolve();
          })
          .catch((_) => {
            this.tableData = [];
            this.form.startDate = "";
            this.form.endDate = "";
            reject();
          })
          .finally((_) => {
            this.loading = false;
          });
      });
    },
    //开始时间
    disabledStartDate(current) {
      if (this.proInfo.uploadEndDate) {
        return moment(moment(current).format("YYYY-MM-DD")).isBefore(
          this.proInfo.uploadEndDate
        );
      } else {
        return moment(moment(current).format("YYYY-MM-DD")).isBefore(
          moment().format("YYYY-MM-DD")
        );
      }
    },

    startDateChange(val) {
      if (!val) {
        this.form.endDate = "";
      } else {
        if (
          moment(moment(this.form.endDate).format("YYYY-MM-DD")).isBefore(val)
        ) {
          this.form.endDate = "";
        }
      }
    },

    //结束时间
    disabledEndDate(current) {
      return moment(moment(current).format("YYYY-MM-DD")).isBefore(
        this.form.startDate
      );
    },

    //邀请专家
    gotoInvite(row) {
      this.inviteModalKey = Date.now();
      this.parameter.uuid = row.evaluationId;
      this.parameter.text = "";
      this.parameter.tenantCode = this.form.tenantCode;
      this.inviteModalVisible = true;
    },
    //查看
    gotoDetail(row) {
      this.oneModalKey = Date.now();
      this.parameter.uuid = row.evaluationId;
      this.parameter.text = "查看";
      this.parameter.tenantCode = this.form.tenantCode;
      this.oneKeyNoticeVisible = true;
    },
    //编辑
    gotoEdit(row) {
      this.inviteModalKey = Date.now();
      this.parameter.uuid = row.evaluationId;
      this.parameter.text = "";
      this.parameter.tenantCode = this.form.tenantCode;
      this.inviteModalVisible = true;
    },
    //select 搜索过滤
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text
          .toLowerCase()
          .indexOf(input.toLowerCase()) >= 0
      );
    },
  },
};
</script>
<style lang="less" scoped>
@primary-color: @primary-color;
.expert-management-container {
  display: flex;
  flex-direction: column;
  .serach-conditions-container {
    background-color: @base-bg-color;
    margin-bottom: 10px;
    box-sizing: border-box;
    padding: 10px 10px 0 10px;
    /deep/.ant-form-item {
      display: flex;
      .ant-form-item-label {
        width: 150px;
        white-space: pre-wrap;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height: 40px;
        line-height: 30px;
        label {
          color: #999999;
        }
      }
      .ant-form-item-control-wrapper {
        flex: 1;
      }
    }
    /deep/.ant-btn {
      margin: 4px 0 0 20px;
    }
  }
  .table-container {
    flex: 1;
    background-color: @base-bg-color;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 10px;
    .header {
      box-sizing: border-box;
      display: flex;
      justify-content: space-between;
      align-items: center;
      height: 42px;
    }
    .main {
      flex: 1;
      height: 100%;
      .model-status {
        width: 60px;
        border-radius: 2px;
        margin: 0 auto;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 14px;
        &.normal {
          background: #f1f2f7;
          color: #aab0bc;
        }
        &.release {
          background: #4bc964;
          color: #fff;
        }
        &.default {
          background: none;
          color: #aab0bc;
        }
      }
    }
  }
}
</style>
